package com.sec.etech.ism.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sec.etech.common.constant.DBConstant;
import com.sec.etech.ism.constant.SignatureConstant;
import com.sec.etech.ism.service.IsmMethodService;
import com.sec.etech.ism.service.IsmTaskService;
import com.sec.etech.sys.util.DbUtil;
import org.openbpm.base.api.exception.BusinessMessage;
import org.openbpm.base.core.util.StringUtil;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class IsmGetMaterialInfoServiceImpl implements IsmMethodService {
    @Resource
    IsmTaskService ismTaskService;

    public IsmGetMaterialInfoServiceImpl() {
    }

    @Override
    public JSONObject call(String sysCode, String serviceCode, JSONObject businessParams) throws Exception {
        JSONObject result = new JSONObject();
        JSONObject object = this.checkAndGetData(businessParams);
        JSONObject resData = this.getMaterialInfo(object);
        ismTaskService.deleteTaskByParams(sysCode, serviceCode, serviceCode, null,
                businessParams.getString(SignatureConstant.INPUT_PARAMS));
        if (resData.containsKey("message") && StringUtil.isNotEmpty(resData.getString("message"))) {
            result.put("flag", "fail");
            result.put("msg", resData.getString("message"));
        } else {
            result.put("flag", "success");
            result.put("data", resData);
        }
        return result;
    }

    //入参检查
    private JSONObject checkAndGetData(JSONObject busParams) throws BusinessMessage {
        JSONObject object = busParams.getJSONObject(SignatureConstant.INPUT_PARAMS);
        if (StringUtil.isEmpty(object.getString("material_no")) && StringUtil.isEmpty(object.getString("num"))) {
            throw new BusinessMessage("请求中material_no、num参数不可全部为空，请检查！");
        }
        return object;
    }

    private JSONObject getMaterialInfo(JSONObject paramsObj) {

        String materialNo = paramsObj.getString("material_no");
        String num = paramsObj.getString("num");
        JdbcTemplate slaveJdbcTemplate = DbUtil.getJdbcTemplate(DBConstant.ETECH_SLAVE);
        JSONObject dataObject = new JSONObject();
        List<Map<String, Object>> partsList = null;
        StringBuffer sqlBuf = new StringBuffer()
                .append("SELECT distinct t1.partsnum,t1.partsname,t1.weight,t1.tips,t1.cooperation_num,t1.billet_size,")
                .append("  t1.parts_incision,t1.chuck_quantity,t1.billet_specifications,t1.billet_max_size,t1.insurance_amount,")
                .append("  t1.parts_section_length,t1.unit_parts_gross_weight,t1.unit_parts_quota,t1.material_SAPnum,t1.drawing_logo,")
                .append("  t1.route1,t1.route2,t1.route3,t1.route4,t1.route5,t1.route6,t1.route7,t1.route8,t1.route9,t1.route10,")
                .append("  t1.route11,t1.route12,t1.route13,t1.parts_SAPnum,t1.billet_SAPnum,t1.billet_num,t1.parts_status,")
                .append("  t1.material_num,t2.metalNumname,")
                .append("  t3.heatname heatTreatmentname,t4.`name` route0name,t5.`name` attributename,t6.`name` metalshortname ")
                .append("FROM prod_parts t1 left join sam_mmd_metalNum t2 on t1.metalNumid=t2.metalNumid")
                .append("  left join prod_parts_z_heat t3 on t1.heatTreatmentid=t3.heatid")
                .append("  left join prod_parts_z_route0 t4 on t1.route0=t4.route0id")
                .append("  left join prod_parts_z_attribute t5 on t1.partsAttributeid=t5.partsAttributeid")
                .append("  left join prod_parts_z_metalshortname t6 on t1.metalShortNameid=t6.metalShortNameid ");
        if (StringUtil.isNotEmpty(materialNo)) {
            sqlBuf.append("where t1.active=1 and t1.parts_SAPnum=? ");
            partsList = slaveJdbcTemplate.queryForList(sqlBuf.toString(), materialNo);
        } else {
            sqlBuf.append("where t1.active=1 and t1.partsnum=? ");
            partsList = slaveJdbcTemplate.queryForList(sqlBuf.toString(), num);
        }
        if (partsList != null && partsList.size() > 0) {
            Map map = partsList.get(0);
            Integer status = map.get("parts_status") != null ? (Integer) map.get("parts_status") : null;
            if (status != null && status > 10) {
                //查询路线X字典--routeX
                String sql = "select routexid,code,name from prod_parts_z_routex where active=1";
                List<Map<String, Object>> routexList = slaveJdbcTemplate.queryForList(sql);
                Map<String, String> routexMap = new HashMap<>();
                for (Map<String, Object> mapTmp : routexList) {
                    routexMap.put(mapTmp.get("routexid").toString(), mapTmp.get("name").toString());
                }
                dataObject.put("type", "parts");
                dataObject.put("partsNum", map.get("partsnum"));
                dataObject.put("partsName", map.get("partsname"));
                dataObject.put("materialNo", map.get("parts_SAPnum"));
                if (status == 20) {
                    dataObject.put("partsStatus", "图纸入库");
                } else if (status == 30) {
                    dataObject.put("partsStatus", "路线入库");
                } else if (status == 40) {
                    dataObject.put("partsStatus", "BOM入库");
                }
                dataObject.put("metalShortName", map.get("metalshortname"));//材料简称
                dataObject.put("attributeName", map.get("attributename"));//零件属性
                dataObject.put("metalNumName", map.get("metalNumname"));//牌号或外购件型号
                dataObject.put("heatTreatment", map.get("heatTreatmentname"));//热处理状态
                dataObject.put("insuranceAmount", map.get("insurance_amount"));//保险量
                dataObject.put("partsSectionLength", map.get("parts_section_length"));//零件断面长度
                dataObject.put("cooperationNum", map.get("cooperation_num"));//合制件数
                dataObject.put("partsIncision", map.get("parts_incision"));//零件切口
                dataObject.put("chuckQuantity", map.get("chuck_quantity"));//夹头量
                dataObject.put("billetSpecifications", map.get("billet_specifications"));//坯料或外购件规格
                dataObject.put("billetSize", map.get("billet_size"));//坯料尺寸
                dataObject.put("billetMaxSize", map.get("billet_max_size"));//坯料合并最长尺寸
                dataObject.put("weight", map.get("weight"));//零件净重
                dataObject.put("unitPartsGrossWeight", map.get("unit_parts_gross_weight"));//零件毛重
                dataObject.put("unitPartsQuota", map.get("unit_parts_quota"));//零件材料消耗定额
                dataObject.put("rawMaterialCode", map.get("material_SAPnum"));//原材料物料号
                dataObject.put("materialNum", map.get("material_num"));//原材料数量
                dataObject.put("billet_num", map.get("billet_num"));//毛坯数量
                dataObject.put("route0Name", map.get("route0name"));//路线0
                dataObject.put("route1Name", map.get("route1") != null ? routexMap.get(map.get("route1").toString()) : null);//路线1
                dataObject.put("route2Name", map.get("route2") != null ? routexMap.get(map.get("route2").toString()) : null);//路线2
                dataObject.put("route3Name", map.get("route3") != null ? routexMap.get(map.get("route3").toString()) : null);//路线3
                dataObject.put("route4Name", map.get("route4") != null ? routexMap.get(map.get("route4").toString()) : null);//路线4
                dataObject.put("route5Name", map.get("route5") != null ? routexMap.get(map.get("route5").toString()) : null);//路线5
                dataObject.put("route6Name", map.get("route6") != null ? routexMap.get(map.get("route6").toString()) : null);//路线6
                dataObject.put("route7Name", map.get("route7") != null ? routexMap.get(map.get("route7").toString()) : null);//路线7
                dataObject.put("route8Name", map.get("route8") != null ? routexMap.get(map.get("route8").toString()) : null);//路线8
                dataObject.put("route9Name", map.get("route9") != null ? routexMap.get(map.get("route9").toString()) : null);//路线9
                dataObject.put("route10Name", map.get("route10") != null ? routexMap.get(map.get("route10").toString()) : null);//路线10
                dataObject.put("route11Name", map.get("route11") != null ? routexMap.get(map.get("route11").toString()) : null);//路线11
                dataObject.put("route12Name", map.get("route12") != null ? routexMap.get(map.get("route12").toString()) : null);//路线12
                dataObject.put("route13Name", map.get("route13") != null ? routexMap.get(map.get("route13").toString()) : null);//路线13
                dataObject.put("tips", map.get("tips"));//零件备注
                if (map.get("drawing_logo") != null && (Integer) map.get("drawing_logo") == 1) {
                    dataObject.put("drawingFlag", "T");//图纸标识（SAP对接标识）
                } else {
                    dataObject.put("drawingFlag", "L");//图纸标识（SAP对接标识）
                }
                dataObject.put("billetSAPnum", map.get("billet_SAPnum"));//毛坯物料号
            } else {
                dataObject.put("message", "该物料号正处于编制中！");
            }
        } else {
            List<Map<String, Object>> comList = null;
            if (StringUtil.isNotEmpty(materialNo)) {
                String sql = "select componentnum,componentname,component_status,component_SAPnum from prod_component where component_SAPnum=? and active=1";
                comList = slaveJdbcTemplate.queryForList(sql, paramsObj.getString("material_no"));
            } else {
                String sql = "select componentnum,componentname,component_status,component_SAPnum from prod_component where componentnum=? and active=1";
                comList = slaveJdbcTemplate.queryForList(sql, num);
            }
            if (comList != null && comList.size() > 0) {
                //Integer status = comList.get(0).get("component_status") != null ? (Integer) comList.get(0).get("component_status") : null;
                // if (status == null || status == 10) {
                //     dataObject.put("message", "该物料号正处于编制中！");
                // } else {
                dataObject.put("type", "component");
                dataObject.put("componentNum", comList.get(0).get("componentnum"));
                dataObject.put("componentName", comList.get(0).get("componentname"));
                dataObject.put("materialNo", comList.get(0).get("component_SAPnum"));
                // }
            } else {
                dataObject.put("message", "该物料号不存在或者已作废！");
            }
        }
        return dataObject;
    }

    @Override
    public String methodName() {
        return "getMaterialInfo";
    }
}
